<?php
require_once('Extension/Controller/Plugin/Abstract.php');

class Extension_Controller_Plugin_Common_Layout extends Extension_Controller_Plugin_Abstract
{
    //public function routeStartup(Zend_Controller_Request_Abstract $request) {}

    public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {
        self::initLayout($request);
    }

    //public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request) {}
    //public function preDispatch(Zend_Controller_Request_Abstract $request) {}
    //public function postDispatch(Zend_Controller_Request_Abstract $request) {}
    //public function dispatchLoopShutdown() {}


    public static function initLayout(Zend_Controller_Request_Abstract $request)
    {
        $moduleName = $request->getModuleName();
        
        require_once('Zend/Registry.php');
        if (false == Zend_Registry::isregistered('Zend_Layout')) {

            $config = Kbs::initConfig('Layout');

            if (null != $config->$moduleName) {

                if (null == $config->$moduleName->layoutPath) {
                    require_once('Extension/Layout/Exception.php');
                    throw new Extension_Layout_Exception('layoutPath of module "' . $moduleName . '" can not be empty !');
                }

                if (null == $config->$moduleName->layout) {
                    require_once('Extension/Layout/Exception.php');
                    throw new Extension_Layout_Exception('layout filename of module "' . $moduleName . '" can not be empty !');
                }

                require_once('Zend/Layout.php');
                $layout = Zend_Layout::startMvc()->setLayoutPath(PROJECT_ROOT . $config->$moduleName->layoutPath)
                                                 ->setLayout($config->$moduleName->layout);

                Zend_Registry::set('Zend_Layout', $layout);
                return $layout;

            } else {
                //require_once('Extension/Layout/Exception.php');
                //throw new Extension_Layout_Exception('layout of module "' . $moduleName . '" missing !');
                return false;
            }

        } else {
            return Zend_Registry::get('Zend_Layout');
        }
    }
}